package com.kamistoat.meimeimall.meimeimallsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ElasticSearch的配置类
 */
@Configuration
public class ElasticSearchConfig {

    @Value("${meimeimallsearch.elasticsearch.hostname}")
    private String hostname;
    @Value("${meimeimallsearch.elasticsearch.port}")
    private Integer port;
    @Value("${meimeimallsearch.elasticsearch.scheme}")
    private String scheme;

    /**
     * 注入ES高阶Client
     * 在项目的其他地方，只需要@Autowired这个RestHighLevelClient类，就可以直接使用client了
     *
     * @return RestHighLevelClient
     */
    @Bean
    public RestHighLevelClient esRestClient() {
        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(
//                        // 这里不知道使用localhost还是用docker暴露的，反正用docker暴露的的最靠谱
//                        new HttpHost("172.19.0.2", 9200, "http")));
                RestClient.builder(
                        new HttpHost(hostname, port, scheme)));
        return client;
    }


    /**
     * 通用的RequestOptionse，命名为COMMON_OPTIONS。用于给请求加请求头等操作，可以在项目的任何地方调用。其使用场景可以总结为：
     * RestHighLevelClient.xxx方法(xxx数据,ElasticSearchConfig.COMMON_OPTIONS)
     */
    public static final RequestOptions COMMON_OPTIONS;
    public static final String TOKEN = "TOKEN";
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }
}

